package black.market.main;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParserException;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.SystemClock;
import black.market.daum.DaumApi;
import black.market.location.LocationDAO;
import black.market.location.MapContentProvider;
import black.market.location.ReadLocation;
import black.market.main.BlackPublic.Action;
import black.market.util.Log;
import black.market.util.Util;
import black.market.weather.KmaInfoDAO;
import black.market.weather.KmaInfoData;
import black.market.weather.WeatherContentProvider;

public class BlackReceiver extends BroadcastReceiver {
	public static final String TAG = "BlackReceiver";
	private ReadLocation readLocation = null;
	private KmaInfoData kmaInfoData = null;
	private LocationDAO locationDAO = null;
	private KmaInfoDAO kmaInfoDAO = null;

	@Override
	public void onReceive(Context context, Intent intent) {
		Context receiveContext = context.getApplicationContext();
		readLocation = new ReadLocation(receiveContext);
		kmaInfoData = new KmaInfoData(receiveContext);
		locationDAO = new LocationDAO(receiveContext);
		kmaInfoDAO = new KmaInfoDAO(receiveContext);
		Log.d(TAG, "intent action: " + intent.getAction());
		// TODO Auto-generated method stub
		if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
			SharedPreferences preferences = receiveContext.getSharedPreferences(Action.SHARED_PREF.toString(), Context.MODE_PRIVATE);
			SharedPreferences.Editor editor = preferences.edit();
			String[] actionArr = { Action.READLOCATION_1H.toString(), Action.KMA_DATA_INTERVAL3H.toString() };
			AlarmManager mAlarmManager = (AlarmManager) receiveContext.getSystemService(Context.ALARM_SERVICE);
			for (int i = 0; i < actionArr.length; i++) {
				intent.setAction(actionArr[i]);
				PendingIntent mPendingIntent = PendingIntent.getBroadcast(receiveContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
				Log.d(TAG, "mPendingIntent:" + mPendingIntent.getTargetPackage());
				if (actionArr[i].equals(Action.READLOCATION_1H.toString())) {
					BlackPublic.identifiesLog(TAG, "readLocationAlarm1Hour_Repeating -> ");
					mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), AlarmManager.INTERVAL_HOUR, mPendingIntent);
					editor.putBoolean(Action.READLOCATION_1H.toString(), true);
				}
				if (actionArr[i].equals(Action.KMA_DATA_INTERVAL3H.toString())) {
					BlackPublic.identifiesLog(TAG, "kmaAlarm3Hour_Repeating -> ");
					mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, AlarmManager.INTERVAL_HOUR * 2, (AlarmManager.INTERVAL_HOUR * 3) + 150000, mPendingIntent);
					editor.putBoolean(Action.KMA_DATA_INTERVAL3H.toString(), true);
				}
			}
			editor.commit();
		}
		switch (Action.toAction(intent.getAction())) {
		case LOCATION_CHANGED_ACTION:
			try {
				if (Util.isUriDatabaseCheck(receiveContext.getContentResolver(), MapContentProvider.MAP_GEOPOINT_URI)) {
					readLocation.startReadLocation(1, 1);
				} else {
					if (readLocation.isbServiceState()) {
						Log.d(TAG, "Service is On -> LOCATION_CHANGED_ACTION: " + intent.getAction());
						readLocation.stopReadLocation();
						DaumApi daumApi = new DaumApi(receiveContext);
						daumApi.geocodeToAddress(locationDAO.getLocation_Lng(), locationDAO.getLocation_Lat(), "WGS84", "simple", "xml");
					} else {
						Log.d(TAG, "Service is off -> LOCATION_CHANGED_ACTION: " + intent.getAction());
						DaumApi daumApi = new DaumApi(receiveContext);
						daumApi.geocodeToAddress(locationDAO.getLocation_Lng(), locationDAO.getLocation_Lat(), "WGS84", "simple", "xml");
					}
				}
			} catch (XmlPullParserException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case KMA_DATA_INTERVAL3H:
			Log.d(TAG, "KMA_DATA_INTERVAL3H: " + intent.getAction());
			String[] locArr = locationDAO.getSimpleAddr();
			if (locArr == null) {
				BlackPublic.errorLog(TAG, "Fail Get SimpleAddr");
				// readLocation.startReadLocation();
			} else {
				if (!kmaInfoDAO.isKmaDatabase_Null(WeatherContentProvider.HEADER_URI)) {
					kmaInfoDAO.deleteWeather_Head();
				}
				if (!kmaInfoDAO.isKmaDatabase_Null(WeatherContentProvider.BODY_URI)) {
					kmaInfoDAO.deleteWeather_Body();
				}
				String expr = "//sido[@name='" + locArr[0] + "']/gugun[@name='" + locArr[1] + "']/dong[@name='" + locArr[2] + "']/@grid";
				kmaInfoData.getKmaData_Interval_3H(receiveContext.getResources(), expr);
			}
			break;
		case READLOCATION_1H:
			Log.d(TAG, "READLOCATION_1H: " + intent.getAction());
			readLocation.startReadLocation(AlarmManager.INTERVAL_HOUR, 1);
			break;
		case GEOCODE_TO_ADDRESS:
			Log.d(TAG, "GEOCODE_TO_ADDRESS: " + intent.getAction());
			break;
		case GET_KMA_DATA:
			Log.d(TAG, "GET_KMA_DATA: " + intent.getAction());
			break;

		default:
			break;
		}
	}
}
